/*
 * buzzer.c
 *
 * Created: 8/19/2013 3:16:46 PM
 *  Author: Ken Arok
 *
 * \brief The driver of Buzzer Device.
 *
 * Copyright (c) 2013 PT Hanindo Automation Solutions. All rights reserved.
 *
 */


#include "timer_counter.h"
#include "buzzer_hal.h"
#include "buzzer.h"

/* Function of turn off Buzzer. */
static TimerFuncVoid_t _funcTurnBuzzerOff;
/* Timer for Buzzer OFF. */
static volatile uint32_t *_tmrBuzzerOff = NULL;
/* Flag for protection. */
static uint8_t _buzzer_flag_off = 0;


/** \brief Turn Buzzer OFF.
 *
 *  @param _tmr	Pointer to obtained timer.
 *
 */
static void prvTurnOffBuzzer(void *_tmr);

/* ------------------------------------------------------------------------------ */
void vBuzzerInit(void)
{
	/* Obtain Timer. */
	_tmrBuzzerOff = vTimer500msTake();
	if(!_tmrBuzzerOff) while(1);
}

void vBuzzerSwitch(const uint8_t _on_off, uint32_t _val)
{
	switch(_on_off)
	{
		case iON:

			/* Turn Buzzer On. */
			buzzer_on();

			/* Check if it is not infinitive ON. */
			if(_val) {
				if(_buzzer_flag_off < 2) {
					*_tmrBuzzerOff = _val * 2;
				}

				if(_buzzer_flag_off == 0) {
					_buzzer_flag_off = 1;
					_funcTurnBuzzerOff = &prvTurnOffBuzzer;
					vTimer500msFuncReg(_funcTurnBuzzerOff, (void *)_tmrBuzzerOff);
				}
			}
		break;
		
		case iOFF:
			/* Turn Buzzer OFF via Timer. */
			if(_buzzer_flag_off < 2) {
				*_tmrBuzzerOff = _val * 2;
			}

			if(_buzzer_flag_off == 0) {
				_buzzer_flag_off = 1;
				_funcTurnBuzzerOff = &prvTurnOffBuzzer;
				vTimer500msFuncReg(_funcTurnBuzzerOff, (void *)_tmrBuzzerOff);
			}
		break;
		
		default: break;
	}
}

/* -------------------------------------------------------------------------- */
static void prvTurnOffBuzzer(void *_tmr)
{
	uint32_t *_ptr = _tmr;

	if(*_ptr == 0) {
		/* Clear protection. */
		_buzzer_flag_off = 0;
		/* Turn Buzzer Off. */
		buzzer_off();
		/* Unregister the function from list. */
		vTimer500msFuncUnreg(_funcTurnBuzzerOff);
		/* Release Timers. */
		vTimer500msGive(_tmr);
	}
}

